package org.summer.lawyer.handle;

import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.summer.lawyer.domain.vo.spuorderassign.SpuOrderAssignVo;
import org.summer.lawyer.event.SpuOrderAssignEvent;
import org.summer.lawyer.service.IMessageService;
import org.summer.lawyer.service.ISpuOrderAssignService;

/**
 * 订单分派处理
 */
@Slf4j
@Getter
@Component
public class SpuOrderAssignHandle implements ApplicationListener<SpuOrderAssignEvent> {

    @Resource
    private SmsService smsService;
    @Resource
    private IMessageService messageService;
    @Resource
    private ISpuOrderAssignService spuOrderAssignService;

    private SpuOrderAssignVo spuOrderAssignVo;

    @Async
    @Override
    public void onApplicationEvent(SpuOrderAssignEvent event) {
        this.spuOrderAssignVo = event.getSpuOrderAssignVo();
        //发送短信
        //判断是不是重新分派
        Long assignCount = spuOrderAssignService.selectSpuOrderAssignCount(spuOrderAssignVo.getOrderId());
        if(assignCount > 1) {
            //查询最近一次撤回记录
            SpuOrderAssignVo lastSpuOrderAssignVo = spuOrderAssignService.selectLastInactiveSpuOrderAssign(spuOrderAssignVo.getOrderId());
            if(lastSpuOrderAssignVo != null) {
                messageService.reallocateLawFirmMsg(spuOrderAssignVo);
                smsService.reallocateLawFirmSms(spuOrderAssignVo.getContactPhone(),spuOrderAssignVo.getUserName(),lastSpuOrderAssignVo.getLawFirmName(), spuOrderAssignVo.getLawFirmName());
            }
        }else{
            messageService.assignLawFirmMsg(spuOrderAssignVo);
            smsService.assignLawFirmSms(spuOrderAssignVo.getContactPhone(),spuOrderAssignVo.getUserName(),spuOrderAssignVo.getSpuName(),spuOrderAssignVo.getLawFirmName(), spuOrderAssignVo.getLawFirmName());
        }
        //发送给律师
        messageService.lawFirmOrderMsg(spuOrderAssignVo);
        smsService.lawFirmOrderSms(spuOrderAssignVo.getContactPhone(),spuOrderAssignVo.getUserName(),spuOrderAssignVo.getSpuName(), spuOrderAssignVo.getLawFirmName());

    }
}
